<template>
  <div class="server-main">
    <el-row :gutter="20">
      <el-col :span="5">
        <el-row class="flex-b whiteBgNew">
          <div class="search-title flex-b-w font16 m-b">
            <span class="blueSpan"></span>文件资源
          </div>
          <div class="search-wrap-left inner-content inner-content-new m-t-20">
            <div class="tree-box">
              <div class="el-input">
                <div class="el-input__wrapper">
                  <input
                    v-model="filterText"
                    class="el-input__inner"
                    type="text"
                    autocomplete="false"
                    placeholder="请输入名称"
                  />
                </div>
              </div>
              <div class="custom-tree-container">
                <el-tree
                  ref="treeRef"
                  class="tree-list filter-tree tree-scrollbar"
                  :data="treeData"
                  draggable
                  node-key="id"
                  :props="defaultProps"
                  accordion
                  :highlight-current="true"
                  :current-node-key="curFolderId"
                  :default-expanded-keys="expandedKeys"
                  :filter-node-method="filterMethod"
                  :expand-on-click-node="false"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <div class="left">
                      <i
                        :class="[
                          'el-icon el-tree-node__expand-icon',
                          {
                            'is-leaf': data.childNum === 0,
                          },
                          {
                            expanded: node.expanded,
                          },
                        ]"
                        @click.prevent="nodeExpand(node, data)"
                      >
                        <i class="el-icon-caret-right"></i>
                      </i>
                      <div
                        @click.prevent="fileExpand(data)"
                        style="width: 100%; display: block"
                      >
                        <img :src="require('@/assets/img/field.png')" />
                        <span class="label ellipsis m-l-10">
                          {{ node.label }}
                        </span>
                      </div>
                    </div>
                    <span class="right">
                      <el-dropdown trigger="click">
                        <i class="el-icon-more"></i>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item
                            @click.native="createSubFolder(data)"
                          >
                            创建子文件夹
                          </el-dropdown-item>
                          <el-dropdown-item
                            @click.native="editFolder(data)"
                            v-if="data.dirName !== '全部'"
                          >
                            重命名
                          </el-dropdown-item>
                          <el-dropdown-item
                            @click.native="deleteFolder(data.id)"
                            v-if="data.dirName !== '全部'"
                          >
                            删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </span>
                  </span>
                </el-tree>
              </div>
            </div>
          </div>
        </el-row>
      </el-col>
      <el-col :span="19">
        <el-form :inline="true" v-model="filterData" class="search-form">
          <el-form-item label="文件名称：" class="form-input">
            <el-input v-model.trim="filterData.file_name"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="km-button"
              size="small"
              type="primary"
              @click="searchSourceData"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <div class="file-table">
          <div class="table-title">
            <span class="table-title-text">源数据管理</span>
            <div class="table-title-button" v-if="curFolderId">
              <el-button
                type="primary"
                class="km-button"
                size="small"
                @click="extractDataAll()"
              >
                抽取【{{ curFolderName }}】下的所有文件</el-button
              >
              <el-button
                type="primary"
                class="km-button"
                size="small"
                @click="extractData()"
                >批量抽取</el-button
              >
              <el-button
                class="km-button"
                size="small"
                type="primary"
                @click="handleSelectFile"
                >上传文件</el-button
              >
              <input
                ref="sourceFileRef"
                type="file"
                multiple
                accept="*"
                @input="readySelectFile"
                style="display: none"
              />
            </div>
          </div>
          <el-table
            ref="sourceTableRef"
            :data="tableList"
            row-key="id"
            v-loading="tableLoading"
            @selection-change="handleSelectionChange"
            class="km-table"
          >
            <el-table-column
              type="selection"
              reserve-selection
              width="50"
              align="center"
            >
            </el-table-column>

            <el-table-column
              label="序号"
              align="center"
              type="index"
              width="50"
            >
            </el-table-column>
            <el-table-column
              prop="fileName"
              label="文件名"
              align="center"
              min-width="350"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="fileSize"
              label="大小（KB）"
              align="center"
              width="150"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="uploadUserName"
              label="上传人"
              align="center"
              width="150"
            ></el-table-column>
            <el-table-column
              prop="uploadTime"
              label="上传时间"
              width="200"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center" width="300">
              <template slot-scope="scope">
                <el-link
                  :underline="false"
                  type="primary"
                  class="form-action"
                  :href="scope.row.fileUrl"
                  :download="scope.row.fileName"
                  >下载</el-link
                >
                <el-link
                  :underline="false"
                  type="primary"
                  class="form-action"
                  @click.native.prevent="previewData(scope.row)"
                  >预览</el-link
                >
                <el-link
                  :underline="false"
                  type="primary"
                  class="form-action"
                  @click.native.prevent="markData(scope.row)"
                >
                  标注</el-link
                >
                <el-link
                  :underline="false"
                  type="primary"
                  class="form-action"
                  @click.native.prevent="extractData(scope.row)"
                  >抽取</el-link
                >
                <el-link
                  :underline="false"
                  type="primary"
                  class="form-action"
                  @click.native.prevent="onDeleteFile(scope.row.id)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="km-pagination"
            background
            :small="true"
            layout="total, prev, pager, next,sizes, jumper"
            :total="total"
            :hide-on-single-page="!total"
            :page-size.sync="filterData.page_size"
            :pager-count="7"
            :page-sizes="[10, 20, 30]"
            :current-page="filterData.page_index"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
        <el-dialog
          title="抽取任务"
          :visible.sync="dialogExtractVisible"
          @close="afterExtractClose"
        >
          <el-form
            ref="dialogExtractForm"
            label-position="left"
            label-width="120px"
            :model="extractForm"
            :rules="extractRules"
          >
            <el-form-item label="抽取任务名称：" prop="extraction_task_name">
              <el-input
                v-model="extractForm.extraction_task_name"
                placeholder="请输入任务名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="抽取类型：" prop="extraction_type">
              <el-radio-group v-model="extractForm.extraction_type">
                <el-radio
                  @change="changeRadio"
                  v-for="r in extractTypeOptions"
                  :key="r.value"
                  :label="r.value"
                  :disabled="
                    (r.value === 3 && !regexpRadioAble) ||
                    (r.value === 4 && !structRadioAble)
                  "
                  style="margin: 10px"
                >
                  {{ r.label }}
                  <template v-if="r.value === 3">
                    <el-tooltip content="正则表达式抽取仅支持doc/docx/txt文件">
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </template>
                  <template v-if="r.value === 4">
                    <el-tooltip
                      content="结构化抽取类型仅支持xls/xlsx/csv格式的单文件"
                    >
                      <i class="el-icon-warning"></i>
                    </el-tooltip>
                  </template>
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="选择抽取算法："
              prop="model_id"
              v-if="extractForm.extraction_type === 1"
            >
              <el-select
                v-model="extractForm.model_id"
                placeholder="请选择"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in extractAlgoList"
                  :key="item.id"
                  :label="item.modelName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="选择抽取模型："
              prop="model_id"
              v-if="extractForm.extraction_type === 6"
            >
              <el-select
                v-model="extractForm.model_id"
                placeholder="请选择"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in extractMBTXList"
                  :key="item.id"
                  :label="item.modelName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="选择抽取模型："
              prop="model_id"
              v-if="extractForm.extraction_type === 2"
            >
              <el-select
                v-model="extractForm.model_id"
                placeholder="请选择"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in extractModelList"
                  :key="item.id"
                  :label="item.modelName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="选择抽取规则："
              prop="model_id"
              v-if="extractForm.extraction_type === 3"
            >
              <el-select
                v-model="extractForm.model_id"
                placeholder="请选择"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in extractRuleList"
                  :key="item.ruleId"
                  :label="item.name"
                  :value="item.ruleId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="本体模型："
              prop="ontology_all_id"
              v-if="extractForm.extraction_type === 2"
            >
              <el-select
                v-model="extractForm.ontology_all_id"
                placeholder="请选择本体模型"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in ontologyModelList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogExtractVisible = false">取消</el-button>
            <el-button @click="extractDataAction(1)">暂存</el-button>

            <el-button
              v-if="extractForm.extraction_type === 4"
              type="primary"
              @click="configStructRule"
              >配置抽取规则</el-button
            >
            <el-button
              v-else
              type="primary"
              @click="extractDataAction"
              :loading="submitDialogLoading"
              >开始抽取</el-button
            >
          </div>
        </el-dialog>
        <el-dialog
          title="数据标注"
          :visible.sync="dialogMarkVisible"
          @close="afterMarkClose"
        >
          <el-form
            ref="dialogMarkForm"
            label-position="left"
            label-width="100px"
            :model="markForm"
            :rules="markRules"
          >
            <el-form-item label-width="0">
              请选择标注该文件时依据的本体模型：
            </el-form-item>
            <el-form-item label="本体模型：" prop="ontology_all_id">
              <el-select
                v-model="markForm.ontology_all_id"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in ontologyModelList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogMarkVisible = false">取消</el-button>
            <el-button type="primary" @click="markDataAction">确定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
    <DataDictionaryDialog
      ref="dataDictRef"
      :dialogTitle="folderDialogTitle"
      :curItem="curItem"
      @initData="initUnit"
    />
  </div>
</template>
<script>
import DataDictionaryDialog from './dataDictionaryDialog.vue';
import { mapState } from 'vuex';
import { Base64 } from 'js-base64';
export default {
  name: 'sourceDataManagement',
  components: {
    DataDictionaryDialog,
  },
  watch: {
    filterText: {
      handler: function (newVal) {
        this.$refs.treeRef?.filter(newVal);
      },
      deep: true,
    },
  },
  data: () => {
    return {
      treeData: [
        {
          id: '0',
          dirName: '全部',
          children: [],
        },
      ],
      defaultProps: {
        label: 'dirName',
        children: 'children',
      },
      curFolderName: '',
      curFolderId: '',
      expandedKeys: [''],
      expandedNode: '',
      expandedData: {
        children: {},
        id: '',
      },
      filterText: '',
      folderDialogTitle: '',
      curItem: {},
      filterData: {
        dir_id: null,
        file_name: '', // 文件名称
        page_index: 1, // 页码
        page_size: 10, // 每页条数
      },
      tableList: [], // 文件列表
      // 表格选中项
      selections: [],
      curExtractRow: null, // 点击单个抽取时赋值 批量抽取置空
      ontologyModelList: [], // 本体模型列表
      extractAlgoList: [], // 抽取算法列表
      extractMBTXList: [], //抽取MBTX列表
      extractModelList: [], // 抽取模型列表
      extractRuleList: [], // 抽取规则列表
      extractTypeOptions: [
        { label: '目标特性抽取', value: 6 },
        { label: '大模型', value: 2 },
        { label: '正则表达式', value: 3 },
        { label: '结构化抽取', value: 4 },
      ], // 抽取类型列表
      tableLoading: false,
      total: 0, // 数据总条数
      dialogExtractVisible: false,
      submitDialogLoading: false,
      extractForm: {
        source_file_dir_id: null,
        extraction_task_name: null,
        extraction_type: 2,
        model_id: null,
        ontology_all_id: null,
        source_file_ids: [],
      },
      extractRules: {
        extraction_task_name: [
          {
            required: true,
            message: '请输入抽取任务名称',
            trigger: 'blur',
          },
        ],
        extraction_type: [
          {
            required: true,
            message: '请选择抽取类型',
            trigger: 'blur',
          },
        ],
        model_id: [
          {
            required: true,
            message: '请选择抽取算法/模型/规则',
            trigger: 'blur',
          },
        ],
        ontology_all_id: [
          {
            required: true,
            message: '请选择抽取模型抽取本体',
            trigger: 'blur',
          },
        ],
      },
      dialogMarkVisible: false,
      markForm: {
        ontology_all_id: null,
        file_id: null,
      },
      markRules: {
        ontology_all_id: [
          {
            required: true,
            message: '请选择本体模型',
            trigger: 'blur',
          },
        ],
      },
      delConfirmLoading: false,
      delTargetFile: null,
      fileExtension: '',
    };
  },
  computed: {
    ...mapState({
      containerDom: (state) => state.server.containerDom,
    }),
    // 结构化抽取是否可选择 条件：单文件 且格式为xls xlsx csv三种之一
    structRadioAble() {
      if (this.extractForm.source_file_ids.length === 1) {
        let fileType = null;
        if (this.curExtractRow) {
          fileType = this.curExtractRow.fileName.split('.').pop().toLowerCase();
        } else {
          fileType = this.selections[0].fileName.split('.').pop().toLowerCase();
        }
        if (['xls', 'xlsx', 'csv'].includes(fileType)) {
          return true;
        }
        return false;
      }
      return false;
    },

    // 正则抽取是否可选择 条件: 格式为doc docx txt三种之一
    regexpRadioAble() {
      if (this.curExtractRow) {
        let fileType = this.curExtractRow.fileName
          .split('.')
          .pop()
          .toLowerCase();
        if (['doc', 'docx', 'txt'].includes(fileType)) {
          return true;
        }
        return false;
      } else {
        let unSupport = this.selections.find((i) => {
          let fileType = i.fileName.split('.').pop().toLowerCase();
          return !['doc', 'docx', 'txt'].includes(fileType);
        });

        return unSupport ? false : true;
      }
    },
  },
  created() {
    this.initUnit();

    // 获取实体模型列表
    this.getOntologyModel();
    // 获取抽取模型列表
    this.getExtractModel();
    // 获取抽取规则列表
    this.getExtractRules();
  },
  methods: {
    // 触发选择文件
    handleSelectFile() {
      this.$refs.sourceFileRef.click();
    },
    // 准备
    readySelectFile() {
      const selectFiles = this.$refs.sourceFileRef.files;
      if (selectFiles.length) {
        for (const file of selectFiles) {
          this.uploadFile({ file });
        }
      }
    },
    // 上传校验文件
    validSelectFile(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1);
      const whiteList = [
        'pdf',
        'doc',
        'docx',
        'xls',
        'xlsx',
        'txt',
        'csv',
        'zip',
        'jpg',
        'tiff',
        'mp3',
        'wav',
        'aac',
        'flac',
        'ogg',
        'm4a',
        'mp4',
        'avi',
        'mkv',
        'mov',
        'wmv',
        'flv',
        'webm',
        'png',
      ];
      // ".pdf, .doc, .docx, .txt, .xls, .xlsx, .csv, .zip, ,jpg, .tiff"
      // "音频：.mp3 .wav .aac .flac .ogg .m4a"
      // "视频：.mp4 .avi .mkv .mov .wmv .flv .webm"
      if (whiteList.indexOf(fileSuffix.toLowerCase()) === -1) {
        this.$message.error(
          '上传文件只能是 pdf、doc、docx、xls、xlsx、txt、csv、zip、jpg、tiff或视频、音频格式'
        );
        return false;
      }
      return true;
    },
    // 上传文件
    uploadFile(e) {
      const formData = new FormData();
      formData.append('source_files', e.file);
      formData.append('user_id', 1);
      let dir_id = this.filterData.dir_id ? this.filterData.dir_id : 0;
      formData.append('dir_id', dir_id);
      this.$api.knowledgeGeneration
        .uploadSourceFile(formData)
        .then((res) => {
          const { code, message } = res.data;
          if (code !== 200) {
            console.error(res);
            this.$message.error(message);
            return;
          }
          this.filterData = {
            ...this.filterData,
            file_name: '', // 文件名称
            page_index: 1, // 页码
          };
          this.$message.success('上传成功');
          this.getSourceDataList(this.filterData);
        })
        .catch((err) => {
          console.error(err);
          this.$message.error('上传失败');
        });
    },
    searchSourceData() {
      this.filterData.page_index = 1;
      // 清空选中项
      this.$refs.sourceTableRef.clearSelection();
      this.getSourceDataList(this.filterData);
    },
    // 获取源数据文件列表
    getSourceDataList(params) {
      const PREFIX = process.env.VUE_APP_API_URL_YUDA;
      this.tableLoading = true;
      this.$api.knowledgeGeneration
        .getSourceDataList(params)
        .then((res) => {
          const { code, data, message } = res.data;
          if (code !== 200) {
            console.error(res);
            this.$message.error(message);
            return;
          }
          this.total = data.total;
          this.tableList = data.list.map((data) => {
            data.fileUrl = PREFIX + data.fileUrl;
            return data;
          });
        })
        .finally(() => (this.tableLoading = false));
    },
    getOntologyModel() {
      this.$api.knowledgeGeneration.getOntologyModel().then((res) => {
        const { code, data, message } = res.data;
        if (code !== 200) {
          console.error(res);
          this.$message.error(message);
          return;
        }
        this.ontologyModelList = data.map((ontologyModel) => ({
          id: ontologyModel.ontologyAllId,
          title: ontologyModel.ontologyAllName,
        }));
      });
    },
    changeRadio() {
      this.extractForm.model_id = null;
      this.getExtractModel();
    },
    // 获取算法和模型数据 modelType值 1：算法 2：模型
    getExtractModel() {
      this.$api.knowledgeGeneration.getExtractModel().then((res) => {
        const { code, data, message } = res.data;
        if (code !== 200) {
          console.error(res);
          this.$message.error(message);
          return;
        }
        this.extractAlgoList = data.filter((e) => e.modelType === 1);
        this.extractMBTXList = data.filter(
          (e) => e.modelType === 7 || e.modelType === 8
        );
        this.extractModelList = data.filter(
          (e) => e.modelType === 2 || e.modelType === 5
        );
      });
    },
    getExtractRules() {
      this.$api.knowledgeGeneration
        .getAllEnableExtractRule()
        .then((res) => {
          const { data, message, code } = res.data;
          if (code === 200) {
            this.extractRuleList = data;
          } else {
            this.$message.warning(message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleSelectionChange(e) {
      this.selections = e;
      console.log(e);
      // this.tableSelected = e.map((e) => e.id);
    },
    // 预览数据
    previewData(row) {
      window.open(
        `${row.previewUrl}/onlinePreview?url=` +
          encodeURIComponent(
            Base64.encode(
              window.location.origin + row.fileUrl.replace(/\\/g, '/')
            )
          )
        //  +
        // '&officePreviewType=html'
      );
    },
    // 标注数据
    markData(fileData) {
      const { id, fileName } = fileData;
      const fileExtension = fileName.split('.').pop().toLowerCase();
      this.fileExtension = fileExtension;
      if (
        fileExtension !== 'docx' &&
        fileExtension !== 'doc' &&
        fileExtension !== 'txt' &&
        fileExtension !== 'png' &&
        fileExtension !== 'jpeg' &&
        fileExtension !== 'jpg'
      ) {
        this.$message.error('只支持 doc、docx、txt,png,jpeg,jpg 格式文件标注');
        return;
      }
      this.markForm.file_id = id;
      this.dialogMarkVisible = true;
    },
    // 抽取校验文件
    validExtractFile(fileName) {
      const fileSuffix = fileName.substring(fileName.lastIndexOf('.') + 1);
      const whiteList = [
        'pdf',
        'doc',
        'docx',
        'txt',
        'xls',
        'xlsx',
        'png',
        'jpg',
        'jpeg',
        'csv',
      ]; // "doc docx pdf txt"
      if (whiteList.indexOf(fileSuffix.toLowerCase()) === -1) {
        this.$message.error(
          '当前只支持抽取doc、docx、pdf、xls、xlsx、png、jpg、jpeg和txt文件'
        );
        return false;
      }
      return true;
    },
    extractDataAll() {
      console.log(
        '%c [  ]-828',
        'font-size:13px; background:pink; color:#bf2c9f;',
        this.curFolderId
      );
      this.extractForm.source_file_dir_id = this.curFolderId;
      this.dialogExtractVisible = true;
    },
    // 抽取数据
    extractData(row) {
      let id = [];
      if (row) {
        if (this.validExtractFile(row.fileName)) {
          this.extractForm.extraction_task_name = row.fileName;
          this.curExtractRow = row;
          id = [row.id];
        } else {
          return;
        }
      } else {
        if (!this.selections.length) {
          return this.$message.warning('请选择要抽取的文件');
        }
        this.curExtractRow = null;
        id = this.selections.map((e) => e.id);
      }
      this.extractForm.source_file_ids = id;
      this.dialogExtractVisible = true;
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.filterData.page_index = page;
      this.getSourceDataList(this.filterData);
    },
    // 修改每页条数
    handleSizeChange() {
      this.getSourceDataList(this.filterData);
    },
    // 抽取弹窗关闭后
    afterExtractClose() {
      this.extractForm = {
        extraction_task_name: null,
        extraction_type: 2,
        model_id: null,
        ontology_all_id: null,
        source_file_ids: [],
      };
      this.$refs.dialogExtractForm.clearValidate();
    },
    // 标注弹窗关闭后
    afterMarkClose() {
      this.markForm = {
        ontology_all_id: null,
        file_id: null,
      };
      this.$refs.dialogMarkForm.clearValidate();
    },
    // 结构化抽取配置规则
    configStructRule() {
      let row;
      if (this.curExtractRow) {
        row = this.curExtractRow;
      } else {
        row = this.selections[0];
      }
      this.$router.push({
        path: '/knowledgeGeneration/extractTask/struct',
        query: {
          name: this.extractForm.extraction_task_name,
          fileName: row.fileName,
          fileId: row.id,
        },
      });
    },
    // 实际执行抽取
    extractDataAction(flag) {
      this.$refs.dialogExtractForm.validate((valid) => {
        if (valid) {
          this.submitDialogLoading = true;
          const params = { ...this.extractForm };
          if (flag === 1) {
            params.temp = 1;
          }
          let loadIns;
          if (flag !== 1) {
            loadIns = this.$message({
              showClose: true,
              dangerouslyUseHTMLString: true,
              duration: 0,
              customClass: 'el-message-loading',
              message: `<div class="el-loading-spinner">
                    <svg viewBox="25 25 50 50" class="circular">
                      <circle cx="50" cy="50" r="15" fill="none" class="path">
                      </circle>
                    </svg>
                  </div>
                  <span class="el-message-loading__text">
                    正在执行任务抽取,请稍候......
                  </span>`,
            });
          }

          this.$api.knowledgeGeneration
            .extractSourceData(params)
            .then((data) => {
              if (data.data.code == 200) {
                this.$message.success(data.data.message);
              } else {
                this.$message.error(data.data.message);
              }
            })
            .catch((error) => {
              this.$message.error('抽取失败');
              console.log(error);
            })
            .finally(() => {
              this.dialogExtractVisible = false;
              this.submitDialogLoading = false;
              loadIns && loadIns.close();
              this.$eventBus.$emit('knowledgeGeneration_extractFinish');
              if (flag !== 1) {
                setTimeout(() => {
                  this.$router.push('/knowledgeGeneration/extractTask');
                }, 500);
              }
            });
        }
      });
    },
    markDataAction() {
      this.$refs.dialogMarkForm.validate((valid) => {
        if (valid) {
          if (
            this.fileExtension == 'png' ||
            this.fileExtension == 'jpeg' ||
            this.fileExtension == 'jpg'
          ) {
            this.$router.push({
              path: '/knowledgeGeneration/annotation/annotationPic',
              query: this.markForm,
            });
          } else {
            this.$router.push({
              path: '/knowledgeGeneration/annotation/annotation',
              query: this.markForm,
            });
          }
        }
      });
    },
    // 删除文件点击事件
    onDeleteFile(id) {
      this.$confirm('此操作将删除此数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.delConfirmLoading = true;
          let data = await this.$api.knowledgeGeneration.deleteSourceData({
            source_data_id: id,
          });
          if (data.data.code !== 200) {
            this.$message.error(data.data.message);
            this.delConfirmLoading = false;
            return;
          }
          this.$message.success('删除成功');
          this.delConfirmLoading = false;
          this.getSourceDataList(this.filterData);
        })
        .catch((err) => {
          this.$message.info('已取消删除');
        });
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    handleChange(file) {
      const _file = file?.raw ?? file;
      const formData = new FormData();
      formData.append('fileList', _file);
      formData.append('directoryId', this.curFolderId);
      this.$axios
        .post(this.$api.dataConnection.fileSource.upload, formData)
        .then(() => {
          // 获取文件列表
          this.getSourceDataList(this.filterData);
          this.closeDialog();
        });
    },
    filterMethod(value, data) {
      return data.dirName?.includes(value);
    },
    // 展开文件夹
    nodeExpand(node, data) {
      this.curFolderId = data.id;
      this.curFolderName = data.dirName;
      node.expanded = !node.expanded;
      data.children = [];
      if (node.expanded) {
        this.expandedNode = node;
        this.expandedData = data;
        this.expandedKeys[0] = data ? data.id : [];
        // this.queryParams.pageNum = 1;
        // this.queryParams.currentPage = 1;
        this.moreUnit(data, node);
        this.filterData.dir_id = this.curFolderId;
        // 获取文件列表
        this.getSourceDataList(this.filterData);
      }
    },
    fileExpand(data) {
      this.checked = false;
      this.curFolderId = data.id;
      this.curFolderName = data.dirName;
      this.expandedData = data;
      this.filterData.dir_id = this.curFolderId ? this.curFolderId : null;
      // 获取文件列表
      this.getSourceDataList(this.filterData);
    },

    moreUnit(item, node) {
      this.$axios
        .get(this.$api.dataConnection.fileSource.getTreeList, {
          params: {
            parentId: Number(item.id),
          },
        })
        .then((res) => {
          const { code, data } = res.data || {};
          if (code === 200) {
            data.forEach((i) => {
              this.$refs.treeRef.append(i, node.key);
            });
          }
        });
    },
    createSubFolder(data) {
      this.folderDialogTitle = '创建子文件夹';
      Object.assign(this.curItem, data);
      this.$refs.dataDictRef.show({ isEdit: 0 });
    },
    editFolder(val) {
      this.folderDialogTitle = '编辑文件夹';

      console.log(
        '%c [  ]-1046',
        'font-size:13px; background:pink; color:#bf2c9f;',
        val
      );
      Object.assign(this.curItem, val);
      this.$refs.dataDictRef.show({ isEdit: 1 });
    },
    deleteFolder(id) {
      this.$confirm(`确定删除此文件夹？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const form = new FormData();
          form.append('idList', id);
          this.$axios
            .post(this.$api.dataConnection.fileSource.deleteFun, form)
            .then((res) => {
              const { code } = res.data || {};
              if (code === 200) {
                this.initUnit();
                // 获取文件列表
                this.getSourceDataList(this.filterData);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
    initUnit() {
      this.$axios
        .get(this.$api.dataConnection.fileSource.getTreeList, {
          params: {
            parentId: 0,
            name: null,
          },
        })
        .then((res) => {
          const { code, data } = res.data || {};
          if (code === 200) {
            console.log(
              '%c [ getTreeList ]-1156',
              'font-size:13px; background:pink; color:#bf2c9f;',
              data
            );
            this.treeData[0].children = data;
            this.curFolderId = this.treeData[0]?.id;
            this.curFolderName = this.treeData[0]?.dirName;
            this.filterData.dir_id = this.curFolderId ? this.curFolderId : null;
            this.expandedKeys = [this.curFolderId];
            // 获取文件列表
            this.getSourceDataList(this.filterData);
            console.log(
              '%c [ this.treeData ]-1164',
              'font-size:13px; background:pink; color:#bf2c9f;',
              this.treeData
            );
          }
        });
    },
  },
};
</script>
<style lang="scss">
.el-message.el-message-loading {
  .el-message__content {
    .el-loading-spinner {
      margin-top: -17px;

      .circular {
        width: 36px;
        height: 36px;
      }

      text-align: left;
    }

    .el-message-loading__text {
      margin-left: 40px;
    }
  }
}
</style>
<style lang="scss" scoped>
.server-main {
  .search-form {
    background: #ffffff;
    border-radius: 4px;
    padding: 16px 32px;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      .el-input,
      .el-select {
        ::v-deep .el-input__inner {
          width: 240px;
          height: 32px;
          background: #ffffff;
          border-radius: 2px;
          border: 1px solid #e0e0e0;
        }
      }
    }
  }
}

.file-table {
  margin-top: 16px;
  padding: 16px 32px 64px;
  background: #ffffff;
  border-radius: 4px;

  .table-title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    &-text {
      margin: 8px 0;
      font-size: 16px;
      line-height: 16px;
      border-left: 5px solid $--color-primary;
      padding-left: 10px;
    }

    &-button {
      display: flex;

      .el-button {
        margin-right: 20px;
      }
    }

    margin-bottom: 10px;
  }
}

.server-main {
  .form-action {
    padding: 0 10px;

    & + .form-action {
      border-left: 1px solid #dddddd;
    }
  }

  ::v-deep .el-dialog {
    width: 500px;
    border-radius: 5px;
  }

  .dialog-inline {
    ::v-deep .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }
}
.whiteBgNew {
  background-color: #fff;
  height: 89vh;
  padding: 20px;
}
.whiteBg {
  background-color: #fff;
  height: 85vh;
  padding: 20px;
}
.white {
  background-color: #fff;
}
.blueSpan {
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #5272ec;
  margin-right: 10px;
  position: relative;
  bottom: 0px;
}
.flex-b-w {
  display: flex;
  align-items: center;
}
.font16 {
  font-size: 16px;
}
.m-b {
  margin-bottom: 20px;
}
.m-l-10 {
  margin-left: 10px;
}
.flex-a-c {
  display: flex;
  justify-content: space-between;
}
:deep(.tree-box) {
  height: 100%;
  overflow-y: auto;
  height: 80vh;
  .collection {
    color: #fff;
    display: flex;
    align-items: center;
    padding-left: 20px;
    height: 26px;
    line-height: 26px;
    cursor: pointer;
    &:hover {
      color: #2f7afc;
      background-color: var(--el-tree-node-hover-bg-color);
    }
    h3 {
      padding-left: 10px;
    }
  }
  .el-tree {
    border: none !important;
    padding: 20px 0 20px 0;
  }
  .custom-tree-container {
    margin-top: 5px;
    min-height: 50vh;
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      .right {
        display: none;
      }
      &:hover .right {
        display: block;
      }
      span {
        color: var(--text-theme-color);
      }
      &:hover span {
        color: #2f7afc;
      }
      .el-icon {
        margin-right: 4px;
        font-size: 18px;
        box-sizing: border-box;
        --color: var(--el-expand-icon);
        &.expanded {
          transform: rotate(90deg);
        }
      }
    }
  }

  .el-tree-node__content {
    position: relative;
    .span-more {
      position: absolute;
      bottom: -22px;
      left: 25%;
      color: #2f7afc;
    }
  }
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #2f7afc;
    .custom-tree-node {
      span {
        color: #fff;
      }
    }
    .el-icon-more {
      color: #fff;
    }
  }
  .el-tree-node__content > .el-tree-node__expand-icon {
    display: none;
  }
  .left {
    display: flex;
    align-items: center;
    width: 100%;
    .label {
      flex: 1;
    }
  }
  .el-tree-node__children {
    width: 100%;
    .el-tree-node .span-more {
      display: none;
    }
    .el-tree-node:last-child .span-more {
      display: block;
    }
  }
  .span-more {
    color: #2f7afc;
  }
}
.tree-box::-webkit-scrollbar {
  display: none;
}
</style>
